package com.smartcruise.util;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;

import com.smartcruise.MyApplication;
import com.smartcruise.data.UserInfo;

import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/2/5 0005
 * 获取当前用户信息的便捷入口
 */

public class TempleUser {

    private String account;
    private String token;
    private UserInfo userInfo;

    /**
     * description:初始化用户信息
     */

    public void init() {
        account = SPUtils.getLastAccount();
        if (account == null) {
            noUserData();
            Log.e("TempleUser", "没有找到id");
            return;
        }
        token = SPUtils.getLastToken();

        try (Realm realm = Realm.getDefaultInstance()) {
            UserInfo templeUserInfo = realm.where(UserInfo.class).equalTo(Key.id, account).findFirst();
            if (templeUserInfo != null) {
                userInfo = realm.copyFromRealm(templeUserInfo);
                Log.d("TempleUser", userInfo.toString());
            } else {
                noUserData();
                Log.e("TempleUser", "没有找到UserInfo");
            }
        }
    }

    /**
     * description:本地没有用户信息 退出APP 让用户重新登录
     */

    private void noUserData() {
        ToastUtils.showShort(MyApplication.getInstance(), "没有找到用户信息，请重新登录");
        MyApplication.getInstance().exitApp();
        PackageManager packageManager = MyApplication.getInstance().getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage("com.smartCruise");
        MyApplication.getInstance().startActivity(intent);
    }

    public String getAccount() {
        if (account == null) {
            init();
        }
        return account;
    }

    public String getToken() {
        if (token == null) {
            init();
        }
        return token;
    }

    public UserInfo getUserInfo() {
        if (userInfo == null) {
            init();
        }
        return userInfo;
    }

    private TempleUser() {

    }

    static class InstanceHolder {
        final static TempleUser instance = new TempleUser();
    }

    public static TempleUser getInstance() {
        return InstanceHolder.instance;
    }
}
